package com.example.shop.merchant.controller;

import com.example.shop.common.api.ResponseResult;
import com.example.shop.common.api.ServiceReturn;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.common.enums.SessionAttributeKey;
import com.example.shop.common.util.FileOptionUtil;
import com.example.shop.merchant.vo.MerchantPublicInfo;
import com.example.shop.merchant.dto.RegisterParam;
import com.example.shop.merchant.service.MerchantService;
import com.example.shop.pojo.Merchant;
import com.example.shop.redis.service.LettuceClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    MerchantService merchantService;
    @Autowired
    LettuceClient redisClient;

    @PostMapping(value = "/register/param/check",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult<Boolean> checkRegisterParam(@Validated RegisterParam registerParam, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
        }
        ServiceReturn<Boolean> result = merchantService.checkRegisterParam(registerParam);
        return  ResponseResult.auto(result.getStateCode(),result.getReturnData());
    }


    @PostMapping(value = "/register",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseResult<Boolean> register(@Validated RegisterParam registerParam, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ResponseResult.failure(ServiceStateCode.PARAMETER_NONSTANDARD);
        }
        ServiceReturn<Boolean> checkResult = merchantService.checkRegisterParam(registerParam);
        if(checkResult.getReturnData()){
            try {
                ServiceReturn<Boolean> result = merchantService.register(registerParam);
                return ResponseResult.auto(result.getStateCode(),result.getReturnData());
            }catch (Exception e){
                e.printStackTrace();
                FileOptionUtil.asyncDeleteDir(Merchant.RESOURCE_ROOT_DIR + registerParam.getAccount(),true);
                return ResponseResult.failure(ServiceStateCode.FAILURE);
            }
        }
        return ResponseResult.booleanResp(checkResult.getStateCode(),checkResult.getReturnData());
    }

    @PostMapping("/login")
    public ResponseResult<MerchantPublicInfo> login(HttpSession session, String account, String password){
        ServiceReturn<Merchant> result = merchantService.login(account, password);
        return loginAfterDeal(session,result);
    }

    public ResponseResult<MerchantPublicInfo> loginAfterDeal(HttpSession session, ServiceReturn<Merchant> result){
        //业务正确处理
        if(result.getStateCode().correctExecBusiness()){
            Merchant merchant = result.getReturnData();
            Merchant nowLoginMerchant = (Merchant) session.getAttribute(SessionAttributeKey.NOW_LOGIN_MERCHANT.getKey());
            //如果当前会话中有商家登录，且 登录的商家跟要登录的商家不是同一
            if(nowLoginMerchant != null && !nowLoginMerchant.getMerchantId().equals(merchant.getMerchantId())){
                //对当前会话中登录的用户进行登出操作
                merchantService.loginOut(nowLoginMerchant);
            }
            //设置当前登录的商家为要登录的商家
            session.setAttribute(SessionAttributeKey.NOW_LOGIN_MERCHANT.getKey(),merchant);
            return ResponseResult.success(MerchantPublicInfo.getMerchantPublicInfo(merchant));
        }
        //有登录有错误，如密码不正确
        return ResponseResult.failure(result.getStateCode());
    }

    @GetMapping(value = "/loginOut",consumes = MediaType.APPLICATION_JSON_VALUE)
    public void loginOut(HttpSession session){
        Merchant merchant = (Merchant) session.getAttribute(SessionAttributeKey.NOW_LOGIN_MERCHANT.getKey());
        if(merchant!=null){
            session.removeAttribute(SessionAttributeKey.NOW_LOGIN_MERCHANT.getKey());
            merchantService.loginOut(merchant);
        }
    }


}
